package com.qf.air.controller;

import com.qf.air.util.ElasticsearchUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 写字楼里写字间，写字间里程序员；
 * 程序人员写程序，又拿程序换酒钱。
 * 酒醒只在网上坐，酒醉还来网下眠；
 * 酒醉酒醒日复日，网上网下年复年。
 * 但愿老死电脑间，不愿鞠躬老板前；
 * 奔驰宝马贵者趣，公交自行程序员。
 * 别人笑我忒疯癫，我笑自己命太贱；
 * 不见满街漂亮妹，哪个归得程序员？
 *
 * @version v1.0
 * @authorLenovo
 * @date2021/11/5
 */
@RestController
@RequestMapping(value = "/air")
@CrossOrigin(allowCredentials = "true")
public class ImageController {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @RequestMapping(value = "/image",method = RequestMethod.GET)
    public List<Map> list() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("air");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.aggregation(AggregationBuilders.terms("image").field("districtName.keyword").size(10));
        searchSourceBuilder.size(0);
        request.source(searchSourceBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        Terms terms = response.getAggregations().get("image");
        List<Map> list = new ArrayList<>();
        for (Terms.Bucket bucket : terms.getBuckets()) {
            Map map = new HashMap();
            map.put("name",bucket.getKey());
            map.put("value",bucket.getDocCount());
            list.add(map);
        }
        return list;
    }
}
